import React, { useEffect, useState } from 'react'
import moment from 'moment';
import { useHistory } from 'dva'
import { newDatetype } from '../../utils/newDate'
import { Space, Table, Tag, Image, Button, Input, Modal, notification, Form, Radio, DatePicker, } from 'antd';
import { Modifytheplaylist, usermanagement, delConsumer, consumeradd, updateuser } from '../../api'
import { ExclamationCircleOutlined, SmileOutlined } from '@ant-design/icons';
import './Consumer.scss'



export default function Consumer() {
    const { Search } = Input;
    const history = useHistory()
    const [Addthesongs] = Form.useForm()
    const [Editindividualplaylists] = Form.useForm()
    const [adduser] = Form.useForm()
    const { confirm } = Modal;
    const [manageplaylists, setManageplaylists] = useState([])
    const [deletes, setDeletes] = useState([])
    const [findlist, setFindlist] = useState([])
    const [value, setValue] = useState(1);

    const [isModalOpen, setIsModalOpen] = useState(false);

    ///
    useEffect(() => {
        getsongadmin()
    }, [])


    const getsongadmin = async () => {
        // usermanagement
        const data = await usermanagement()
        // console.log(data)
        data.forEach(item => {
            item.key = item.id
        })
        setManageplaylists(data)
        setFindlist(data)
    }

    const showModal = () => {
        setIsModalOpen(true);
    };
    //添加新用户
    const handleOk = async () => {
        const arr = Addthesongs.getFieldsValue(true)
        arr.birth = newDatetype(arr.birthtime)
        // console.log(data)
        console.log(arr)
        let params = new URLSearchParams();
        params.append('username', arr.username);
        params.append('password', arr.password);
        params.append('sex', arr.sex);
        params.append('phoneNum', arr.phoneNum);
        params.append('email', arr.email);
        params.append('introduction', arr.introduction);
        params.append('location', arr.location);
        params.append('birth', arr.birth);
        params.append('avator', "https://img2.baidu.com/it/u=2161457492,303957051&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=400");
        const data = await consumeradd(params);
        // console.log()

        notification.open({
            message: '添加成功',
            duration: 1,
            icon: (
                <SmileOutlined
                    style={{
                        color: '#108ee9',
                    }}
                />
            ),
        });


        getsongadmin();
        // console.log(data)
        setIsModalOpen(false);
        Addthesongs.resetFields()
    };
    const handleCancel = () => {
        setIsModalOpen(false);
        Addthesongs.resetFields()
    };

    //新增,点击事件
    const Thenewsonglist = (val) => {
        showModal()
    }
    ///////
    //编辑
    const Editbox = (val) => {
        setOpen(true);
        val.birthtime = [moment(val.birth, "YYYY-MM-DD")][0]
        Editindividualplaylists.setFieldsValue(val)
    }
    const [open, setOpen] = useState(false);
    const Ok = async (val) => {
        const arr = Editindividualplaylists.getFieldsValue(true)
        console.log(arr)
        let params = new URLSearchParams();
        params.append('username', arr.username);
        params.append('password', arr.password);
        params.append('sex', arr.sex);
        params.append('phoneNum', arr.phoneNum);
        params.append('email', arr.email);
        params.append('introduction', arr.introduction);
        params.append('location', arr.location);
        params.append('birth', arr.birth);
        params.append('id', arr.id);
        await updateuser(params)
        getsongadmin()
        Editindividualplaylists.resetFields()
        setOpen(false)
    };
    const Cancel = () => {
        Editindividualplaylists.resetFields()

        setOpen(false);

    };
    const columns = [
        {
            title: '用户图片',
            dataIndex: 'avator',
            key: 'id',
            fixed: 'left',
            width: 180,
            align: 'center',
            render: (item, text, index) => {
                return (
                    <div>
                        <Image
                            width={100}
                            height={100}
                            src={item}
                        />
                    </div>
                )
            },
        },
        {
            title: '用户名',
            dataIndex: 'username',
            key: 'id',
            align: 'center',
        },
        {
            title: '性别',
            dataIndex: 'sex',
            key: 'id',
            width: 100,
            align: 'center',
            render: (item, text, index) => (
                item = item ? "男" : "女"
            )
        },
        {
            title: '手机号',
            dataIndex: 'phoneNum',
            key: 'id',
            align: 'center',
        },
        {
            title: '电子邮箱',
            dataIndex: 'email',
            key: 'id',
            align: 'center',
        },
        {
            title: '生日',
            dataIndex: 'birth',
            key: 'id',
            align: 'center',
        },
        {
            title: '签名',
            dataIndex: 'introduction',
            key: 'id',
            align: 'center',
        },
        {
            title: '地区',
            dataIndex: 'location',
            key: 'id',
            align: 'center',
        },
        {
            title: '操作',
            key: 'id',
            fixed: 'right',
            width: 180,
            align: 'center',
            render: (item, text, index) => {
                return <div className='dellist'><Button onClick={() => Editbox(item)}>编辑</Button>&nbsp;&nbsp;&nbsp;&nbsp;<Button onClick={() => dellist('success', item.id)} danger>删除</Button></div>
            }
        },
    ];
    //获取需要删除项的id
    const tableSelectionChange = (val) => {
        // console.log(val)
        setDeletes(val)
    }
    //批量删除模块
    const dellist = (type, val) => {
        // console.log(val)
        confirm({
            title: '确认永久删除吗',
            icon: <ExclamationCircleOutlined />,
            content: '删除后不可恢复',
            async onOk() {
                val === undefined ? deletes.forEach(a => delConsumer(a).then(a => {
                    getsongadmin()
                })) : delConsumer(val).then(a => {
                    getsongadmin()
                })
                notification[type]({
                    message: '删除成功',
                    duration: 1,
                });
            },
        });
    }



    const onSearch = async (value) => {
        var s = JSON.stringify(findlist)
        var d = JSON.parse(s)
        var html = [];
        let arrnew = d.map((item, index) => {
            return Object.assign(
                {},
                {
                    id: item.id,
                    username: item.username,
                    avator: item.avator,
                    email: item.email,
                    sex: item.sex,
                    birth: item.birth,
                    introduction: item.introduction,
                    location: item.location,
                }
            );
        });
        var newData = arrnew.filter((item) => {
            console.log(item.username)
            if (item.username.indexOf(value) > -1) {
                return item;
            }
            return newData;
        });
        if (newData.length > 0) {
            for (var i = 0; i < newData.length; i++) {
                html.push(newData[i])
            }
        }
        html.forEach(a => {
            a.key = a.id
        })
        setManageplaylists(html)
    };




    const validateMessages = {
        required: '${label} is required!',
        types: {
            email: '${label} 格式不正确',
            number: '${label} is not a valid number!',
        },
        number: {
            range: '${label} must be between ${min} and ${max}',
        },
    };

    return (
        <div id='Consumer'>
            <div className='consumer-box'>
                <Button onClick={() => dellist('success')} danger>批量删除</Button>&nbsp;&nbsp;&nbsp;&nbsp;
                <Search placeholder="查询用户" onSearch={onSearch} enterButton />&nbsp;&nbsp;&nbsp;&nbsp;
                <Button onClick={() => Thenewsonglist()}>添加新用户</Button>
                <br />
                <br />
                <br />
            </div>
            <Modal title="添加新用户" open={isModalOpen} onOk={handleOk} onCancel={handleCancel} >
                <Form
                    name="nest-messages"
                    form={Addthesongs}
                    validateMessages={validateMessages}
                >
                    <Form.Item
                        label="用户名"
                        name="username"
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="密码"
                        name="password"

                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="性别"
                        name="sex"
                    >
                        <Radio.Group value={value}>
                            <Radio value={1}>A</Radio>
                            <Radio value={2}>B</Radio>
                        </Radio.Group>
                    </Form.Item>

                    <Form.Item
                        label="手机号"
                        name="phoneNum"
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="电子邮箱"
                        name={['name', 'email']}
                        rules={[
                            {
                                type: 'email',
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="生日"
                        name="birthtime"
                    >
                        <DatePicker />

                    </Form.Item>

                    <Form.Item
                        label="签名"
                        name="introduction"
                    >
                        <Input />
                    </Form.Item>


                    <Form.Item
                        label="地区"
                        name="location"
                    >
                        <Input />
                    </Form.Item>
                    {/* 头像 avator */}
                </Form>
            </Modal>
            <Table
                rowSelection={{
                    type: "checkbox",
                    onChange: tableSelectionChange,
                }}
                scroll={{
                    x: 2000,
                    y: 500,
                }}
                bordered
                columns={columns} dataSource={manageplaylists}
            />;

            <Modal title="编辑歌单" open={open} onOk={Ok} onCancel={Cancel}>
                <Form
                    name="basic"
                    form={Editindividualplaylists}
                >
                    <Form.Item
                        label="用户名"
                        name="username"
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="密码"
                        name="password"
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="性别"
                        name="sex"
                    >
                        <Radio.Group value={value}>
                            <Radio value={1}>A</Radio>
                            <Radio value={2}>B</Radio>
                        </Radio.Group>
                    </Form.Item>

                    <Form.Item
                        label="手机号"
                        name="phoneNum"
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="电子邮箱"
                        name="email"
                    >
                        <Input />
                    </Form.Item>


                    <Form.Item
                        label="生日"
                        name="birthtime"
                    >
                        <DatePicker />

                    </Form.Item>

                    <Form.Item
                        label="签名"
                        name="introduction"
                    >
                        <Input />
                    </Form.Item>


                    <Form.Item
                        label="地区"
                        name="location"
                    >
                        <Input />
                    </Form.Item>
                </Form>
            </Modal>


        </div>
    )
}
